<?php

namespace App\Http\Controllers\Html;

use App\Http\Controllers\Controller;
use App\Services\Api\Api;
use File;

class HtmlPage extends Controller
{

    public function index()
    {
        $this->htmlIndexPage();
    }

    protected function htmlIndexPage()
    {
        $pageInfo = config('cms.html_page_info.index');
        $pathInfo = $this->_getStaticFilePath($pageInfo);
        $obj = new Api();
        foreach ($pageInfo['ceil_api_no_list'] as $key => $value) {
            if ($value['flag'] == 'cms') {
                $this->htmlCmsCeilData($obj, $pathInfo['ceil_file_path'], $key, $value);
            } elseif ($value['flag'] == 'api') {

            } else if ($value['flag'] == 'cache') {

            }
            $indexPageViewData[$key] = $pathInfo['ceil_file_path'] . '/' . $key . '.html';
        }
        $indexPageViewData['selectedMenu'] = parent::MENU_INDEX;
        $indexPageViewData['seo'] = $this->returnSeoInfo('tanwin_index');
        $result = $this->_htmlCeilOrPage($pageInfo['blade_path'], $pageInfo['page_html_path'], 'index.html', $indexPageViewData);
        var_dump($result);

    }

    protected function htmlCmsCeilData($obj, $ceilFilePath, $ceilHtmlName, $data)
    {
        $ceilCode = $data['ceil_api_no'];
        $result = $obj->getJavaCeilData(parent::CEIL_API_ID, $ceilCode);
        $viewData = [
            'dataList' => $result['elements'],
        ];
        $this->_htmlCeilOrPage($data['blade_path'], $ceilFilePath, $ceilHtmlName . '.html', $viewData);

    }

    private function _htmlCeilOrPage($bladePath, $filePath, $fileName, $viewData)
    {
        try {
            $htmlContent = view($bladePath, $viewData)->render();
            $fileRealPath = $filePath . '/' . $fileName;
            File::put($fileRealPath, $htmlContent);
            return true;
        } catch (\Exception $e) {
            return $e->getMessage();
            return false;
        }
    }

    private function _getStaticFilePath($pageInfo)
    {
        $staticPageHtmlFilePath = public_path() . '/' . $pageInfo['page_html_path'];
        $staticCeilHtmlFilePath = public_path() . '/' . $pageInfo['ceil_html_path'];
        (!is_dir($staticPageHtmlFilePath)) ? (@mkdir($staticPageHtmlFilePath, 0755, true)) : "";
        (!is_dir($staticCeilHtmlFilePath)) ? (@mkdir($staticCeilHtmlFilePath, 0755, true)) : "";
        return [
            'page_file_path' => $staticPageHtmlFilePath,
            'ceil_file_path' => $staticCeilHtmlFilePath,
        ];
    }
}
